package com.school.sdk.haikang.helper;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.school.sdk.haikang.CommonMethod.osSelect;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.Instant;
import java.util.Date;
import java.util.Properties;

@Slf4j
public class PostAlarmDataUtils {

    public static String appServerHost;
    public static short appServerPort;
    public static short appAlarmPort;
    public static String lepay_device_detail_url;
    public static String lepay_receive_alarm_url;

    public static final String winConfigFilePath = "D:\\haikang\\school-hk-msg-push.properties";
    public static final String winPicBasePath = "D:\\haikang\\pic\\";
    public static final String winLogBasePath = "D:\\haikang\\log\\";
    public static final String winSdkBasePath = "D:\\haikang\\winlib\\";

    public static final String linuxConfigFilePath = "/home/lepei-attached-prischool/haikang/school-hk-msg-push.properties";
    public static final String linuxPicBasePath = "/home/lepei-attached-prischool/haikang/pic/";
    public static final String linuxLogBasePath = "/home/lepei-attached-prischool/haikang/log/";
    public static final String linuxSdkBasePath = "/home/lepei-attached-prischool/haikang/linuxlib/";

    public static void initConfigProperties() {
        String propertiesFilePath = null;
        if (osSelect.isLinux()) {
            validateFilePath(linuxConfigFilePath);
            validateFilePath(linuxPicBasePath);
            validateFilePath(linuxLogBasePath);
            validateFilePath(linuxSdkBasePath);

            propertiesFilePath = linuxConfigFilePath;
        } else {
            validateFilePath(winConfigFilePath);
            validateFilePath(winPicBasePath);
            validateFilePath(winLogBasePath);
            validateFilePath(winSdkBasePath);

            propertiesFilePath = winConfigFilePath;
        }
        Resource resource = new FileSystemResource(new File(propertiesFilePath));
        Properties properties = null;
        try {
            properties = PropertiesLoaderUtils.loadProperties(resource);

            appServerHost = properties.getProperty("app-server-host");
            appServerPort = Short.parseShort(properties.getProperty("app-server-port"));
            appAlarmPort = Short.parseShort(properties.getProperty("alarm-server-port"));
            lepay_device_detail_url = properties.getProperty("get-device-detail-url");
            lepay_receive_alarm_url = properties.getProperty("receive-alarm-url");

        } catch (Exception e) {
            throw new RuntimeException(propertiesFilePath + "解析异常，请检查");
        }
        validateEmptyValue("程序运行ip", appServerHost);
        validateEmptyValue("程序运行端口", appServerPort);
        validateEmptyValue("报警上报端口", appAlarmPort);
        validateEmptyValue("设备详情获取接口地址", lepay_device_detail_url);
        validateEmptyValue("报警上报推送接口地址", lepay_receive_alarm_url);
    }

    public static void validateFilePath(String filePath) {
        if (!FileUtil.exist(filePath)) {
            throw new RuntimeException(filePath + "不存在");
        }
    }

    public static void validateEmptyValue(String name, Object value) {
        if (ObjectUtils.isEmpty(value)) {
            throw new RuntimeException(name + "为空");
        } else {
            log.info("【{}】-->【{}】", name, value);
        }
    }

    public static final String local_pic_url_temp = "http://%s:%s/postAlarm/picFile/%s";

    public static int fire_alarm_code = 201;

    public static int throw_alarm_code = 202;

    public static String getPicBaseName(int code) {
        return (osSelect.isWindows() ? winPicBasePath : linuxPicBasePath) + code + "_" + DateUtil.format(Date.from(Instant.now()), "yyyyMMddHHmmssSSS") + RandomUtil.randomString(8).toUpperCase() + ".jpg";
    }

    public static void sendHaiKangMsg(String alarmDvIp, String filePath, String filePath2, int alarmCode) {

        JSONObject deviceInfo=null;
        if (StrUtil.isBlank(filePath2)) {
            filePath2 = filePath;
        }

        //获取设备信息最多1s
        String getDvDetailUrl= lepay_device_detail_url+"?deviceIp="+alarmDvIp;
        try {
            HttpResponse response = HttpRequest.get(getDvDetailUrl).setConnectionTimeout(1000).execute();
            String resStr = response.body();
            JSONArray array = JSONUtil.parseObj(resStr).getJSONArray("data");
            deviceInfo = array.getJSONObject(0);
        } catch (Exception e) {
            log.error("查询海康设备详情失败：【{}】->【{}】",getDvDetailUrl,e.getMessage());
        }

        String dvId = "7";
        String  dvName = "海康设备" + alarmDvIp;
        String address = "海康设备" + alarmDvIp;
        Integer gatewayNodeId = 1;
        String deviceCode = "";
        if(deviceInfo!=null){
            dvId=deviceInfo.getStr("id");
            dvName=deviceInfo.getStr("deviceName");
            address=deviceInfo.getStr("deviceAddress");
            //gatewayNodeId=deviceInfo.getInt("gatewayNodeId");
            deviceCode=deviceInfo.getStr("deviceCode");
        }else {
            log.info("海康设备不存在" + alarmDvIp);
            return;
        }
        
        sendMsg(formatLocalPic(filePath), alarmCode, ObjectUtils.nullSafeEquals(throw_alarm_code, alarmCode) ? "高空抛物" : "火点检测", dvId, dvName, address,gatewayNodeId, deviceCode, formatLocalPic(filePath2));
    }

    public static final String fire_alarm_fixed_pic_url = "https://campuscdn.lepayedu.com/e544e366c690495c93741c9d763ea0fb.png";

    public static void sendMsg(String picUrl, int algorithmld, String algorithmName, String dvId, String dvName, String address,int gatewayNodeId, String deviceCode, String picUrl2) {
        try {
            JSONObject bodyObject = new JSONObject();
            bodyObject.set("notificationId", IdUtil.getSnowflake().nextIdStr());
            JSONObject paramJson = new JSONObject();
            paramJson.set("algorithmId", algorithmld);
            paramJson.set("algorithmName", algorithmName);
            paramJson.set("eventTime", Date.from(Instant.now()).getTime());
            paramJson.set("eventAddress", address);
            paramJson.set("deviceId", dvId);
            paramJson.set("gatewayNodeId", gatewayNodeId);

//            if (ObjectUtils.isEmpty(picUrl)) {
//                picUrl =fire_alarm_fixed_pic_url;
//            }
            paramJson.set("bigUrl", picUrl);
            paramJson.set("smallUrl", picUrl2);
            paramJson.set("deviceName", dvName);
            //设备国标码
            paramJson.set("deviceCameraCode", deviceCode);
            bodyObject.set("AlarmEventDto", paramJson);

            String body = bodyObject.toString();
            log.info("【HK-ALARM推送请求】-->{}->{}", dvName,algorithmName);
            HttpResponse res = HttpRequest.post(lepay_receive_alarm_url).body(body).execute();
            log.info("【HK-ALARM推送响应】-->{}", res.body());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String formatLocalPic(String filePath) {
        File file = new File(filePath);
        String name = file.getName();
        return String.format(local_pic_url_temp, appServerHost, appServerPort, name);
    }


//    public static String url = "https://ssoplate.lepayedu.com/atta-api/attach/uploadFile";
//    public static String file_middle_token = "1093090425296138288";

    public static String lepay_upload_file_url = "http://work.lepayedu.com:28001/atta-api/attach/uploadFile";
    public static String file_middle_token = "1093090425296138241";

    public static String vue_ecb_key = "!*&1sf1&!@13&ecb";

    public static String uploadPic2Cloud(String filePath) {
        String picLpUrl = null;
        try {
            File file = new File(filePath);

            RestTemplate restTemplate = new RestTemplate();

            FileSystemResource fileSystemResource = new FileSystemResource(file);

            MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
            params.add("file", fileSystemResource);

            String func = "tinymce①content";
            params.add("func", func);
            params.add("lan", true);
            params.add("token", file_middle_token);
            long secondTimestamp = Instant.now().getEpochSecond();
            params.add("timestamp", secondTimestamp);

            String combStr = func + file_middle_token + secondTimestamp;
            String sign = AES.aes256ECBPkcs7Encrypt(combStr, vue_ecb_key);

            params.add("reqSign", sign);
            params.add("file", new FileSystemResource(file));

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
            JSONObject result = restTemplate.postForObject(lepay_upload_file_url, requestEntity, JSONObject.class);
            Object o = result.getJSONObject("data").getJSONArray("child").get(0);
            JSONObject child = JSONUtil.parseObj(o);
            picLpUrl = child.getStr("fullUrl");
            if (!ObjectUtils.isEmpty(picLpUrl)) {
//                FileUtil.del(filePath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("upload pic[{}]->lepay[{}]", filePath, picLpUrl);
        return picLpUrl;
    }
    //demo
    public static void writeImageFile(HttpServletResponse resp, InputStream inputStream) {
        OutputStream out = null;
        try {
            out = resp.getOutputStream();
            int len = 0;
            byte[] b = new byte[1024];
            while ((len = inputStream.read(b)) != -1) {
                out.write(b, 0, len);
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
